package qnb._common.tools;

import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

public class StringTool {
	private final static char str__ = '_';
	
	/**
	 * 是否是数字
	 * @param str
	 * @return
	 */
    public static boolean isNumeric(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }
	/**
	 * 将 xxXX 转成 xx_xx 这种格式的字符串 同时过滤',防注入
	 * 
	 * @param name 字符串
	 * @return String
	 */
	public static String formatStringNameToSqlName(String name) {
		if (null == name || name.isEmpty() || name.contains("'"))
			return name;
		char[] cs = name.toCharArray();
		StringBuilder sb = new StringBuilder(cs.length);
		for (char c : cs) {
			if (Character.isUpperCase(c)) {
				sb.append(str__).append(Character.toLowerCase(c));
			} else {
				sb.append(Character.toLowerCase(c));
			}
		}
		return sb.toString();
	}

	@SuppressWarnings("unchecked")
	public static <T>List<T> jsonStringToList(Class<T> c, String str) {
		ObjectMapper mapper = new ObjectMapper();
		JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, c);
		Object obj;
		try {
			obj = mapper.readValue(str, javaType);
			if (null != obj) {
				return (List<T>) obj;
			}
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}
